﻿using System;
using System.Net;
using System.Xml.Linq;

namespace Songhay.Net
{
    using Models;
    using Xml;

    /// <summary>
    /// Static members for <see cref="System.Net.WebRequest"/>.
    /// </summary>
    public static partial class HttpVerbAsyncUtility
    {
        /// <summary>
        /// Gets the <see cref="OpmlDocument"/>.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="getDocumentCompleteAction">The get-document-complete action.</param>
        public static void GetOpmlDocument(Uri resourceIndicator,
            Action<OpmlDocument> getDocumentCompleteAction)
        {
            if(getDocumentCompleteAction == null)
                throw new ArgumentNullException("getDocumentCompleteAction",
                    "The generic Action is null.");

            HttpVerbAsyncUtility.Get(resourceIndicator,
                new Action<object, DownloadStringCompletedEventArgs>(
                    (o, args) =>
                    {
                        if(args.Error != null)
                            throw new WebException("Problem getting OPML document.", args.Error);

                        var xd = XDocument.Parse(args.Result);
                        var opml = OpmlUtility.GetDocument(xd.Root, OpmlUtility.rx);
                        getDocumentCompleteAction.Invoke(opml);
                    }
                ));
        }
    }
}
